package com.test.controller;

import com.test.entity.RestBean;
import com.test.service.ImageService;
import io.minio.GetObjectArgs;
import io.minio.errors.*;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

@RestController
public class GetObjectController {
    @Resource
    ImageService service;

    @GetMapping("/images/**")
    public RestBean<String> getAvatar(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String imageUrl = request.getServletPath().substring(7);
        response.setContentType("image/jpg");


        if (imageUrl.length() <= 13) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            response.setContentType("application/json;charset=UTF-8");
            return RestBean.failure(404, "图片不存在");
        }

        try {
            // 假设 service.fetchImage 返回一个 InputStream 或者直接写入到 ServletOutputStream
            service.fetchImage(imageUrl, response.getOutputStream());
            response.setHeader("Cache-Control", "max-age=604800");
            response.setContentType("image/jpeg");

            return RestBean.success();
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.setContentType("application/json;charset=UTF-8");
            return RestBean.failure(500, "服务器错误");
        }
    }
}
